package dq.study.minimvc.util;

import dq.study.minimvc.HandlerInterceptor;
import dq.study.minimvc.annotation.Listener;
import dq.study.minimvc.annotation.RequestMapping;
import dq.study.minimvc.annotation.RestController;
import dq.study.minimvc.reflect.HandlerMethod;

import java.io.File;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 权限分配工具类
 * @author dongqun
 * 2018年1月31日下午1:21:25
 */
public class ScanPackageUtil {
	/**
	 * 初始化各类角色能访问的接口 
	 * 以类名.函数名的形式存储
	 * @author dongqun
	 * 2018年1月31日下午2:01:41
	 * @param packageName
	 * @return
	 */
	public static Map<String, Object> scanPackage(String packageName){
		Map<String, Object> handlers = new HashMap<>();
		List<HandlerInterceptor> interceptors = new ArrayList<>();
		try {
			List<String> classes = getClassByPackage(packageName);
			for (String c : classes) {
				String name = packageName+"."+c.substring(0, c.lastIndexOf(".class"));
				Class<?> cls =  Class.forName(name);
				if (cls.isAnnotationPresent(Listener.class)){
					interceptors.add((HandlerInterceptor) cls.newInstance());
				}
				if (!cls.isAnnotationPresent(RestController.class)) continue;
				String prefix = null;
				if (cls.isAnnotationPresent(RequestMapping.class)){
					prefix = cls.getAnnotation(RequestMapping.class).value();
				}
				Method[] methods = cls.getDeclaredMethods();
				for (Method method : methods) {
					if (!method.isAnnotationPresent(RequestMapping.class)) {
						continue;
					}
					RequestMapping requestMapping = method.getAnnotation(RequestMapping.class);
					String url = requestMapping.value();
					if (prefix!=null) url = prefix + url;
					HandlerMethod handlerMethod = new HandlerMethod(cls.newInstance(),method);
					handlers.put(url,handlerMethod);
				}
			}
			handlers.put("listener",interceptors);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return handlers;
	}
	
	private static List<String> getClassByPackage(String packageName){
		List<String> result = new ArrayList<>();
		String pname = packageName.replace(".", "/");
		String path = ScanPackageUtil.class.getClassLoader().getResource(pname).getPath();
		File file = new File(path);
		String[] files = file.list();
		for (String name : files) {
			String subPath = path + "/" + name;
			File subFile = new File(subPath);
			if (subFile.isDirectory()) {
				String[] files1 = subFile.list();
				for (String name1 : files1) {
					String subPath1 = path + "/" + name + "/" +name1;
					File subFile1 = new File(subPath1);
					if (subFile1.getName().endsWith(".class")) {
						String name2 = name + "." + name1;
						result.add(name2);
					}
				}
				
			}else{
				if (subFile.getName().endsWith(".class")) {
					result.add(name);
				}
			}
		}
		return result;
	}

	public static void main(String[] args) {
		System.out.println(scanPackage("com.sun.cms.web.controller"));
	}

	

}
